#include "s3eKeyboard.h"
#include "s3ePointer.h"
#include "s3eDevice.h"
#include <time.h>

#include "Iw2D.h"
#include "IwResManager.h"

#include "title.h"
#include "game.h"
#include "variables.h"
#include "random.h"

// Entry point
// The main() function initialises application data and required Airplay modules; it then
// enters a while() loop that exits only when the application throws a "quit" event. Each
// iteration of this loop performs a general "update" and "render" of the application. If the
// loop exits, application data is deleted and Airplay modules are terminated before exiting.
int main(int argc, char* argv[])
{
    // Initialisation of Airplay Studio modules
    Iw2DInit();         // Initialise support for rendering with the standard SW renderer
    IwResManagerInit();

    // Load all application data
    IwGetResManager()->LoadGroup("math.group");

	Title* title = new Title;
    Game* game = new Game;

    uint32 timer = (uint32)s3eTimerGetMs();

    while(true)
    {
		//Enables the device OS to do other things while running the game
        s3eDeviceYield(0);

        // Check for user quit
        if (s3eDeviceCheckQuitRequest())
            break;

        // Calculate the amount of time that's passed since last frame
        int delta = uint32(s3eTimerGetMs()) - timer;
        timer += delta;

        // Make sure the delta-time value is safe
        if (delta < 0)
            delta = 0;
        if (delta > 100)
            delta = 100;

        if (gameMode == MODE_TITLE)
        {
			title->Update(delta);
            title->Render();

            // When starting a new game, make sure we reset the state
            if (gameMode == MODE_GAMEPLAY)
			{
				//Reset all game variables for new round of play
				game->Reset();
			}
        }
        else
        {
            game->Update(delta);
            game->Render();
        }

        //Present the rendered surface to the screen
        Iw2DSurfaceShow();
    }

    // Delete objects and terminate systems
	delete title;
	delete game;
	Random::Instance()->Destroy();

    // Terminate system modules
    IwResManagerTerminate();
    Iw2DTerminate();

    return 0;
}
